package com.bjsxt;
//使用字符串作为线程对象锁
/*所有线程在执行synchronized时都会同步
 *  synchronized("字符串"){ 同步代码 }*/

/*定义程序员类*/
class Programmer02{
    private String name;
    public Programmer02(String name){
        this.name=name;
    }
    //打开电脑
    public void computer(){
        //放在方法中
        // public synchronized void computer(){
        //synchronized public void computer(){
        synchronized (this) {
            try {
                System.out.println(this.name + "接通电源");
                Thread.sleep(500);
                System.out.println(this.name + "按下开机键");
                Thread.sleep(500);
                System.out.println(this.name + "系统启动中");
                Thread.sleep(500);
                System.out.println(this.name + "系统启动成功");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    //编码
    public void coding(){
        synchronized (this) {
            try {
                System.out.println(this.name + "双击IDEA");
                Thread.sleep(500);
                System.out.println(this.name + "Idea启动完毕");
                Thread.sleep(500);
                System.out.println(this.name + "写代码");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    //去卫生间
    public void wc(){
        //让所有线程都有互斥关系，字符串写什么都可以  并行改为串行
        synchronized ("s") {
            try {
                System.out.println(this.name + "打开卫生间门");
                Thread.sleep(500);
                System.out.println(this.name + "开始排泄");
                Thread.sleep(500);
                System.out.println(this.name + "冲水");
                Thread.sleep(500);
                System.out.println(this.name + "离开卫生间");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
//打开电脑的工作线程
class Working03 extends Thread{
    private Programmer02 p;
    public Working03(Programmer02 p){
        this.p=p;
    }
    @Override
    public void run() {
        this.p.computer();
    }
}
//编写代码的线程
class Working04 extends Thread{
    private Programmer02 p;
    public Working04(Programmer02 p){
        this.p=p;
    }
    @Override
    public void run() {
        this.p.coding();
    }
}
//卫生间线程
class Wc extends Thread{
    private Programmer02 p;
    public Wc(Programmer02 p){
        this.p=p;
    }
    @Override
    public void run() {
        this.p.wc();
    }
}
public class TestStringSynchronized {
    public static void main(String[] args) {
        Programmer02 p = new Programmer02("小明");
       /* new Working03(p).start();
        new Working04(p).start();*/
       Programmer02 p2 = new Programmer02("小蓝");
       new Wc(p).start();
       new Wc(p2).start();

    }
}
